<template>
  <section class="todoapp">
    <TodoHeader @add="addFn" :arr="list"></TodoHeader>
    <TodoMain :arr="showList" @del="delFn"></TodoMain>
    <TodoFooter
      :arr="list"
      @clearDone="clearDoneFn"
      @changeType="changeTypeFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 样式引入 + 导入组件并注册使用
import "./styles/base.css";
import "./styles/index.css";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  data() {
    return {
      t: "all",
      list: JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem(JSON.stringify("todos", newVal));
      },
    },
  },

  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  computed: {
    showList() {
      if (this.t === "active") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.t === "ok") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
  },
  methods: {
    changeTypeFn(type) {
      this.t = type;
    },
    // 清除已完成的
    clearDoneFn() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    // 添加
    addFn(name) {
      this.list.unshift({
        id: +new Date(),
        name,
        isDone: false,
      });
    },
    // 删除
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
  },
};
</script>
